package com.zhan.rkforum.controller;


import com.zhan.rkforum.bean.Event;
import com.zhan.rkforum.event.EventProducer;
import com.zhan.rkforum.service.LikeService;
import com.zhan.rkforum.util.CommunityConstant;
import com.zhan.rkforum.util.CommunityUtil;
import com.zhan.rkforum.util.HostHolder;
import com.zhan.rkforum.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;

@Controller
public class LikeController implements CommunityConstant {

    @Autowired
    private LikeService likeService;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @PostMapping("/like")
    @ResponseBody
    public String like(int entityType, int entityId, int entityUserId, int postId){
        likeService.like(entityType, entityId, entityUserId);
        Long likeCount = likeService.getEntityLikeCount(entityType, entityId);
        int status = likeService.getLikeStatus(entityType, entityId, entityUserId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("likeCount", likeCount);
        map.put("status", status);

        //触发点赞事件
        if(status == 1){
            Event event = new Event();
            event.setTopic(TOPIC_LIKE)
                    .setUserId(hostHolder.getUser().getId())
                    .setEntityId(entityId)
                    .setEntityType(entityType)
                    .setEntityUserId(String.valueOf(entityUserId))
                    .setData("postId", postId);
            eventProducer.fireEvent(event);
        }

        if(entityType == ENTITY_TYPE_POST){
            //计算贴子分数
            String postScoreKey = RedisKeyUtil.getPostScoreKey();
            redisTemplate.opsForSet().add(postScoreKey, postId);
        }


        return CommunityUtil.getJsonString(0, null, map);
    }





}
